package components;

import java.awt.Color;
import java.awt.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

import domain.Copy;
import domain.Loan;

public class BookDetailCellRenderer implements ListCellRenderer<Copy> {

    JLabel renderLabel = new JLabel();
    DateFormat dateFormat = SimpleDateFormat.getDateInstance();

    public BookDetailCellRenderer() {
        renderLabel.setOpaque(true);
    }

    @Override
    public Component getListCellRendererComponent(JList<? extends Copy> list, Copy obj, int row, boolean isSelected, boolean hasFocus) {

        Copy copy = (Copy) obj;
        Loan loan = null;

        for (Loan l : copy.getLoans()) {
            if (l.isLent()) {
                loan = l;
                break;
            }
        }

        if (loan == null) {
            renderLabel.setText(copy.getInventoryNumber() + ": Verfügbar");
        } else if (loan.isOverdue()) {
            renderLabel.setText(copy.getInventoryNumber() + ": Ausgeliehen bis " + dateFormat.format(loan.getDueDate().getTime()) + " ("
                    + loan.getDaysOverdue() + " Tage überfällig)");
        } else {
            renderLabel.setText(copy.getInventoryNumber() + ": Ausgeliehen bis " + dateFormat.format(loan.getDueDate().getTime()) + " (noch "
                    + loan.getDaysLeft() + " Tage)");
        }

        if (isSelected) {
            renderLabel.setBackground(new Color(list.getSelectionBackground().getRGB()));
            renderLabel.setForeground(new Color(list.getSelectionForeground().getRGB()));
        } else {
            renderLabel.setBackground(new Color(list.getBackground().getRGB()));
            renderLabel.setForeground(new Color(list.getForeground().getRGB()));
        }

        return renderLabel;
    }
}
